package net.easyjava.tools.http.request;

import net.easyjava.tools.BaseTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wenxiaoning on 15/12/19.
 */
public class RequestTools extends BaseTools {
    private static final long serialVersionUID = 8292930169268627450L;
    private static Logger logger = LoggerFactory.getLogger(RequestTools.class);

    /**
     * 获取用户真实IP
     * @param request
     * @return
     */
    public static String getIP(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if("127.0.0.1".equals(ip)){
                //根据网卡取本机配置的ip
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    logger.error(e.getMessage(), e.fillInStackTrace());
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为真实的IP，多个IP按照','分割
        if(ip != null && ip.length() > 15){
            if(ip.indexOf(",") > 0){
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 获取request head信息中host信息
     * @param request
     * @return
     */
    public static String getHeadHost(HttpServletRequest request){
        return request.getHeader(RequestConstants.HEAD_HOST);
    }

    /**
     * 获取request head信息中referer信息
     * @param request
     * @return
     */
    public static String getHeadReferer(HttpServletRequest request){
        return request.getHeader(RequestConstants.HEAD_REFERER);
    }
    /**
     * 获取request head信息中 User-Agent 信息
     * @param request
     * @return
     */
    public static String getHeadUserAgent(HttpServletRequest request){
        return request.getHeader(RequestConstants.HEAD_USER_AGENT);
    }

    /**
     * 获取request param 参数
     * @param request
     * @return
     */
    public static Map<String,String> getParams(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Enumeration<String> names = request.getParameterNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            params.put(name,request.getParameter(name));
        }
        return params;
    }

    /**
     * 获取param值，不带默认值
     * @param request
     * @param name
     * @return
     */
    public static String getParam(HttpServletRequest request,String name){
        return getParam(request, name, null);
    }

    /**
     * 获取param值
     * @param request
     * @param name
     * @param defaultValue 如果value为null，并且默认值不为null，则返回默认值
     * @return
     */
    public static String getParam(HttpServletRequest request,String name,String defaultValue){
        String value = request.getParameter(name);
        if(value == null && defaultValue != null){
            value = defaultValue;
        }
        return value;
    }

    /**
     * 获取param值
     * @param request
     * @param name
     * @param defaultValue 如果value为null，并且默认值不为null，则返回默认值
     * @return
     */
    public static Integer getParamInteger(HttpServletRequest request,String name,String defaultValue){
        String value = getParam(request, name, defaultValue);

        try {
            return Integer.valueOf(value);
        }catch (NumberFormatException e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }

    /**
     * 获取param值
     * @param request
     * @param name
     * @param defaultValue 如果value为null，并且默认值不为null，则返回默认值
     * @return
     */
    public static Long getParamLong(HttpServletRequest request,String name,String defaultValue){
        String value = getParam(request, name, defaultValue);

        try {
            return Long.valueOf(value);
        }catch (NumberFormatException e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }

    /**
     * 获取header值，不带默认值
     * @param request
     * @param name
     * @return
     */
    public static String getHeader(HttpServletRequest request,String name){
        return getHeader(request, name, null);
    }

    /**
     * 获取header值
     * @param request
     * @param name
     * @param defaultValue 如果value为null，并且默认值不为null，则返回默认值
     * @return
     */
    public static String getHeader(HttpServletRequest request,String name,String defaultValue){
        String value = request.getHeader(name);
        if(value == null && defaultValue != null){
            value = defaultValue;
        }
        return value;
    }

    /**
     * 获取request head 参数
     * @param request
     * @return
     */
    public static Map<String,String> getHeads(HttpServletRequest request){
        Map<String,String> heads = new HashMap<String,String>();
        Enumeration<String> names = request.getHeaderNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            heads.put(name,request.getHeader(name));
        }
        return heads;
    }

    /**
     * 获取request真实请求地址
     * @param request
     * @return
     */
    public static String getRealUrl(HttpServletRequest request){
        return request.getRequestURL().toString();
    }




    public static void main(String[] args) {
        String firefox = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:42.0) Gecko/20100101 Firefox/42.0";
        String safari = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/8.0.7 Safari/600.7.12";
        String chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
        
        String[] user = firefox.split(" ");
        for (int i = 0; i < user.length; i++) {
            System.out.println("user[i] = " + user[i]);

        }
    }


}
